package edu.uow.devdocs

import grails.converters.JSON
import java.io.File;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
//import uk.co.desirableobjects.ajaxuploader.exception.FileUploadException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import uk.co.desirableobjects.ajaxuploader.AjaxUploaderService;
import uk.co.desirableobjects.ajaxuploader.exception.FileUploadException;

class AttachmentController {
	
	AjaxUploaderService ajaxUploaderService
	
	static scaffold = true

    def index() { }
	
	def getAttachment(Integer id) {
		def attachment = Attachment.get(id)
		response.setContentType(attachment.contentType)
		response.setHeader("Content-Disposition", "attachment; filename=\""+attachment.originalFilename+"\"");
		response.outputStream << attachment.fileContents
		response.outputStream.flush()
	}
	
	
	def saveAttachment() {

		try {

			File uploaded = createTemporaryFile()
			InputStream inputStream = selectInputStream(request)

			ajaxUploaderService.upload(inputStream, uploaded)
			
			def attachmentInstance = new Attachment()
			if (params?.issueId) attachmentInstance.issue = Issue.get(params.int('issueId'))
			if (params?.developmentTaskId) attachmentInstance.developmentTask = DevelopmentTask.get(params.int('developmentTaskId'))
			if (params?.developmentChecklistId) attachmentInstance.developmentChecklist = DevelopmentChecklist.get(params.int('developmentChecklistId'))
			if (!attachmentInstance.filename) {
				attachmentInstance.filename = params.qqfile
			}
			attachmentInstance.fileContents = uploaded.getBytes()
			if (attachmentInstance.validate()) {
				attachmentInstance.originalFilename = params.qqfile
				attachmentInstance.filesize = uploaded.size()
				attachmentInstance.contentType = 'application/octet-stream'
				attachmentInstance.save()

			}
			if (attachmentInstance.hasErrors()) {
				def errors  = ""
				attachmentInstance.errors.allErrors.each{
					errors += it
					println it
				}
				return render(text: [success:false] as JSON, contentType:'text/json')
			} else {
				return render(text: [success:true] as JSON, contentType:'text/json')
			}

			return render(text: [success:true] as JSON, contentType:'text/json')

		} catch (FileUploadException e) {

			log.error("Failed to upload file.", e)
			return render(text: [success:false] as JSON, contentType:'text/json')

		}

	}
	
	private InputStream selectInputStream(HttpServletRequest request) {
		if (request instanceof MultipartHttpServletRequest) {
			MultipartFile uploadedFile = ((MultipartHttpServletRequest) request).getFile('qqfile')
			return uploadedFile.inputStream
		}
		return request.inputStream
	}
	
	private File createTemporaryFile() {
		File uploaded = File.createTempFile('grails', 'ajaxupload')
		return uploaded
	}
	
	def getAttachmentList(Integer issueId, Integer developmentChecklistId, Integer developmentTaskId) {
		render(template:"/shared/attachmentList", model:['issueId':issueId,'developmentChecklistId':developmentChecklistId,'developmentTaskId':developmentTaskId])
		
	}
	
	def delete(Integer attachmentId, Integer issueId, Integer developmentChecklistId, Integer developmentTaskId) {
		def attachment = Attachment.get(attachmentId)
		attachment.delete(flush: true)
		render(template:"/shared/attachmentList", model:['issueId':issueId,'developmentChecklistId':developmentChecklistId,'developmentTaskId':developmentTaskId])
	}
	
}
